#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <netinet/in.h>



void *handle_client(void *arg){
    char *recv_buf=malloc(sizeof(char)*1024);
    char *send_buf=malloc(sizeof(char)*50);
    int client_fd = *(int *)arg;

    //客户端连接上了服务器
    printf("client %d connected\n", client_fd);
    memset(recv_buf, 0, sizeof(recv_buf));
    while (recv(client_fd, recv_buf, sizeof(recv_buf), 0) > 0){
        //写进控制台
        printf("recv from client %d: %s\n", client_fd, recv_buf);
        //将数据写进send_buf
        memset(send_buf, 0, sizeof(send_buf));
        memset(recv_buf, 0, sizeof(recv_buf));
        sprintf(send_buf, "server recv success");
        sleep(1);
        send(client_fd, send_buf, strlen(send_buf), 0);
    }

    printf("client %d disconnected\n", client_fd);
    free(send_buf);
    free(recv_buf);
    shutdown(client_fd, SHUT_RDWR);

}



int main(int argc, char const *argv[])
{   
    //创建socket
    int socket_fd= socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server_addr;
    server_addr.sin_port = htons(8888);
    server_addr.sin_addr.s_addr = inet_addr("192.168.13.66");
    server_addr.sin_family = AF_INET;
    bind(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    listen(socket_fd, 128);
    

    while (1)
    {   
        
        //创建客户端的地址
        struct sockaddr_in client_addr;
        socklen_t client_addr_len = sizeof(client_addr);
        int client_fd = accept(socket_fd, (struct sockaddr *)&client_addr, &client_addr_len);
        printf("client %s connected\n", inet_ntoa(client_addr.sin_addr));
        //创建线程
        pthread_t tid;
        pthread_create(&tid, NULL, handle_client, (void *)&client_fd);
        pthread_detach(tid);

    }

    return 0;
}
